<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Vue3键盘事件教学</title>
		<script src="js/vue.js"></script>
	</head>
	<style>
		.box {
			width: 100px;
			height: 100px;
			background-color: blue;
			position: absolute;
			top: 0;
			eft: 0;
		}
	</style>
	<body>
		<div id="app" @keyup='pressKey'>
			弹起来:<input @keyup='getKey' /> <br>
			按下去:<input @keydown.enter='login' />
			<h1 align=center>{{letter}}</h1>
			上下左右移动div
			<div class="box" :style="{ top: boxTop + 'px', left: boxLeft + 'px' }"></div>
		</div>
		<script>
			//创建 销毁
			Vue.createApp({
				data() {
					return {
						letter: 'A',
						boxTop: 0,
						boxLeft: 0,

					}
				},
				created() { //创建完成 没有元素 生命周期函数 不需要触发

				},
				mounted() { //挂载完成
					document.addEventListener('keydown', this.pressKey);
				},
				methods: {
					pressKey(event) {
						if (event.key === "ArrowUp") {
							this.boxTop -= 10;
						} else if (event.key === "ArrowDown") {
							this.boxTop += 10;
						} else if (event.key === "ArrowLeft") {
							this.boxLeft -= 10;
						} else if (event.key === "ArrowRight") {
							this.boxLeft += 10;
						}
						console.log(event)
						this.letter = event.key
					},
					login() {
						alert('登录')
					},
					getKey(event) { //自带参数：事件对象
						console.log(event)
						if (event.keyCode == 13) { //回车 登录
							alert('登录')
						}
					}
				},
			}).mount('#app')
		</script>
	</body>
</html>